package co.com.smart.eagle.bean.rol;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.PersistenceException;

import co.com.smart.eagle.entities.EagleSecurityRoles;
import co.com.smart.eagle.infrastructure.dto.RolesDTO;
import co.com.smart.eagle.infrastructure.dto.SmartExcepcionSerializada;
import co.com.smart.eagle.mapper.Mapper;
import co.com.smart.eagle.persistence.entity.RolFacadeLocal;
import co.com.smart.eagle.session.DelegateContextEJB;

/**
 * Session Bean implementation class RolBean
 */
@Stateless
public class RolBean implements RolBeanLocal {

	private RolFacadeLocal facade;

	/**
	 * Default constructor.
	 */
	public RolBean() {
		facade = DelegateContextEJB.getRolFacadeLocal();
	}

	@Override
	public List<RolesDTO> getRoles() {
		List<RolesDTO> roles = new ArrayList<RolesDTO>();

		List<EagleSecurityRoles> rolesEntity = facade.findAll();
		if (rolesEntity != null) {
			for (EagleSecurityRoles eagleSecurityRoles : rolesEntity) {
				roles.add(Mapper.mapperRoles(eagleSecurityRoles));
			}
		}

		return roles;
	}

	@Override
	public void setRol(RolesDTO rol) throws Exception {
		
		EagleSecurityRoles entityRol = facade.find(rol.getDsRol());
		if (entityRol != null) {
			throw new SmartExcepcionSerializada("El rol ya existe, por favor usar otro");
		}
		entityRol = Mapper.mapperEntityRol(rol);
		facade.create(entityRol);
	}

	@Override
	public void deleteRol(RolesDTO rol)throws Exception {
		try{
			EagleSecurityRoles entityRol =	Mapper.mapperEntityRol(rol);
			facade.remove(entityRol);
		} catch (PersistenceException ex) {
			throw new SmartExcepcionSerializada("No es posible eliminar el registro, Dependencia de datos");
		}
	}

}
